package cn.zhixiangsingle.impl.equipmentmaintenance;

import cn.zhixiangsingle.config.DynamicDataSourceContextHolder;
import cn.zhixiangsingle.dao.equipmentMaintenance.EquipmentMaintenanceMapper;
import cn.zhixiangsingle.dao.site.SiteMapper;
import cn.zhixiangsingle.dao.slipperyAlert.SlipperyAlertMapper;
import cn.zhixiangsingle.date.DateUtils;
import cn.zhixiangsingle.entity.base.IsEmptyUtils;
import cn.zhixiangsingle.entity.base.site.SiteData;
import cn.zhixiangsingle.entity.base.site.vo.SiteVO;
import cn.zhixiangsingle.entity.equipmentmaintenance.dto.EquipmentMaintenanceDTO;
import cn.zhixiangsingle.entity.equipmentmaintenance.vo.EquipmentMaintenanceVO;
import cn.zhixiangsingle.entity.slippery.slipperyAlert.dto.SlipperyAlertDTO;
import cn.zhixiangsingle.entity.slippery.slipperyAlert.vo.SlipperyAlertVO;
import cn.zhixiangsingle.impl.fromWall.FromWallAlertServiceImpl;
import cn.zhixiangsingle.pagination.MyStartEndUtil;
import cn.zhixiangsingle.service.equipmentmaintenance.EquipmentMaintenanceService;
import cn.zhixiangsingle.service.slipperyAlert.SlipperyAlertService;
import cn.zhixiangsingle.web.responsive.IStatusMessage;
import cn.zhixiangsingle.web.responsive.ResultBean;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;


/**
 * @author zn
 * @description  设备维修信息业务层
 * @date 2019/11/16 17:41
 * @Copyright: 2019 www.zhixiangyun.net Inc. All rights reserved.
 * 注意：本内容仅限于浙智飨科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service(version = "1.0.0", interfaceClass = EquipmentMaintenanceService.class)
public class EquipmentMaintenanceServiceImpl implements EquipmentMaintenanceService {

    private static final Logger logger = LoggerFactory
            .getLogger(FromWallAlertServiceImpl.class);
    @Autowired
    private SiteMapper siteMapper;
    @Autowired
    private EquipmentMaintenanceMapper equipmentMaintenanceMapper;

    /**
     * @描述
     * @参数 [equipmentMaintenancetDTO]
     * @返回值 cn.zhixiangsingle.web.responsive.ResultBean
     * @创建人 zn
     * @创建时间 2019/11/16
     * @修改人和其它信息
     */
    @Override
    public ResultBean findEquipmentMaintenanceList(EquipmentMaintenanceDTO equipmentMaintenanceDTO) throws Exception {
        ResultBean resultBean = new ResultBean();
        if (IsEmptyUtils.isEmpty(equipmentMaintenanceDTO.getPage())) {
            equipmentMaintenanceDTO.setPage(1);
        }
        if (IsEmptyUtils.isEmpty(equipmentMaintenanceDTO.getLimit())) {
            equipmentMaintenanceDTO.setLimit(10);
        }
        Integer page = equipmentMaintenanceDTO.getPage();
        Integer limit = equipmentMaintenanceDTO.getLimit();
        StringBuffer stringBufferJson = new StringBuffer();
        InputStream stream = getClass().getClassLoader().getResourceAsStream("json/siteData.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            stringBufferJson.append(line);
        }
        JSONObject jobj = JSON.parseObject(stringBufferJson.toString());

        List<Map<String, Object>> mainLPLs = Lists.newArrayList();
        Integer total = 0;
        int startNum = (page - 1) * limit;
        int endNum = startNum + limit;
        ArrayList<Integer> totalAll = Lists.newArrayList();
        equipmentMaintenanceDTO.setId(-1);
        equipmentMaintenanceDTO.setAgent("a");
      equipmentMaintenanceDTO.setConfirmor("c");
        equipmentMaintenanceDTO.setEquipmentMainame("e");
        equipmentMaintenanceDTO.setModelSpecification("m");
        equipmentMaintenanceDTO.setReasons("r");
        equipmentMaintenanceDTO.setResponSiblepersion("r");
        equipmentMaintenanceDTO.setSaveAddress("s");
        equipmentMaintenanceDTO.setUnit("u");
        equipmentMaintenanceDTO.setUsePersion("u");
        equipmentMaintenanceDTO.setConfirmresult(-1);
        if (!IsEmptyUtils.isEmpty(equipmentMaintenanceDTO.getSdIds())) {
            String[] sdIds = equipmentMaintenanceDTO.getSdIds().split(",");
            StringBuffer stringBuffer = new StringBuffer();
            for (String sdId : sdIds) {
                equipmentMaintenanceDTO.setSdId(Integer.parseInt(sdId));
                String dataSourceName = "";
                SiteData siteData = null;
                if (!IsEmptyUtils.isEmpty(jobj.get(sdId))) {
                    siteData = JSON.parseObject(jobj.get(sdId).toString(), SiteData.class);
                }
                equipmentMaintenanceDTO.setPicturePrefix(siteData.getPicturePrefix());
                if (!IsEmptyUtils.isEmpty(siteData)) {
                    dataSourceName = siteData.getDateSourceName();
                }
                if (!IsEmptyUtils.isEmpty(dataSourceName)) {
                    if (IsEmptyUtils.isEmpty(stringBuffer)) {
                        stringBuffer.append(sdId);
                    } else {
                        stringBuffer.append("," + sdId);
                    }
                    logger.info("--" + dataSourceName + "--");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);
                    Integer totalStatus = equipmentMaintenanceMapper.findEquipmentMaintenanceTotal(equipmentMaintenanceDTO);
                    total = total + totalStatus;
                    totalAll.add(totalStatus);
                }
            }
            ArrayList<ArrayList<Integer>> startEndNums = MyStartEndUtil.getStartEndArray(totalAll, startNum, endNum);
            String[] sourceNames = stringBuffer.toString().split(",");
            for (int i = 0; i < startEndNums.size(); i++) {
                equipmentMaintenanceDTO.setSdId(Integer.parseInt(sourceNames[i]));
                SiteData siteData = JSON.parseObject(jobj.get(sourceNames[i]).toString(), SiteData.class);
                equipmentMaintenanceDTO.setPicturePrefix(siteData.getPicturePrefix());
                logger.info("--" + siteData.getDateSourceName() + "--");
                DynamicDataSourceContextHolder.setDataSourceType(siteData.getDateSourceName());
                equipmentMaintenanceDTO.setStart(startEndNums.get(i).get(0));
                equipmentMaintenanceDTO.setEnd(startEndNums.get(i).get(1) - startEndNums.get(i).get(0));
                equipmentMaintenanceDTO.setSdId(Integer.parseInt(sourceNames[i]));
                equipmentMaintenanceDTO.setSiteName(siteData.getName());
                equipmentMaintenanceDTO.setSitePhoto(siteData.getPhoto());

                List<Map<String, Object>> mainLPList = equipmentMaintenanceMapper.findEquipmentMaintenanceList(equipmentMaintenanceDTO);
                mainLPLs.addAll(mainLPList);
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        } else {
            List<SiteVO> userSites = siteMapper.findUserSites(equipmentMaintenanceDTO.getUserId());
            StringBuffer stringBuffer = new StringBuffer();
            for (SiteVO siteVO : userSites) {
                equipmentMaintenanceDTO.setSdId(siteVO.getSdId());
                String dataSourceName = "";
                String sdIdStr = siteVO.getSdId().toString();
                SiteData siteData = null;
                if (!IsEmptyUtils.isEmpty(jobj.get(sdIdStr))) {
                    siteData = JSON.parseObject(jobj.get(sdIdStr).toString(), SiteData.class);
                }
                equipmentMaintenanceDTO.setPicturePrefix(siteData.getPicturePrefix());
                if (!IsEmptyUtils.isEmpty(siteData)) {
                    dataSourceName = siteData.getDateSourceName();
                }
                if (!IsEmptyUtils.isEmpty(dataSourceName)) {
                    if (IsEmptyUtils.isEmpty(stringBuffer)) {
                        stringBuffer.append(siteVO.getSdId());
                    } else {
                        stringBuffer.append("," + siteVO.getSdId());
                    }
                    logger.info("null sdIds...--" + dataSourceName + "----");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);
                    Integer totalStatus = equipmentMaintenanceMapper.findEquipmentMaintenanceTotal(equipmentMaintenanceDTO);
                    total = total + totalStatus;
                    totalAll.add(totalStatus);
                }
            }
            ArrayList<ArrayList<Integer>> startEndNums = MyStartEndUtil.getStartEndArray(totalAll, startNum, endNum);
            String[] sourceNames = stringBuffer.toString().split(",");
            for (int i = 0; i < startEndNums.size(); i++) {
                SiteData siteData = JSON.parseObject(jobj.get(sourceNames[i]).toString(), SiteData.class);
                logger.info("--" + siteData.getDateSourceName() + "--");
                equipmentMaintenanceDTO.setPicturePrefix(siteData.getPicturePrefix());
                equipmentMaintenanceDTO.setSdId(Integer.parseInt(sourceNames[i]));
                DynamicDataSourceContextHolder.setDataSourceType(siteData.getDateSourceName());
                equipmentMaintenanceDTO.setStart(startEndNums.get(i).get(0));
                equipmentMaintenanceDTO.setEnd(startEndNums.get(i).get(1) - startEndNums.get(i).get(0));
                equipmentMaintenanceDTO.setSdId(Integer.parseInt(sourceNames[i]));
                equipmentMaintenanceDTO.setSiteName(siteData.getName());
                equipmentMaintenanceDTO.setSitePhoto(siteData.getPhoto());

                List<Map<String, Object>> mainLPList = equipmentMaintenanceMapper.findEquipmentMaintenanceList(equipmentMaintenanceDTO);
                mainLPLs.addAll(mainLPList);
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }
        resultBean.setSuccess(true);
        resultBean.setResult(mainLPLs);
        resultBean.setTotal(total);
        resultBean.setResultCode(IStatusMessage.SystemStatus.SUCCESS.getCode());
        resultBean.setMsg(IStatusMessage.SystemStatus.SUCCESS.getMessage());
        return resultBean;
    }

    /**
     * @描述
     * @参数 [equipmentMaintenanceDTO]
     * @返回值 java.util.List<cn.zhixiangsingle.web.responsive.ResultBean>
     * @创建人 zn
     * @创建时间 2019/11/16
     * @修改人和其它信息
     */
    @Override
    public List<ResultBean> getEquipmentMaintenance(EquipmentMaintenanceDTO equipmentMaintenanceDTO) throws Exception {
        StringBuffer stringBufferJson = new StringBuffer();
        InputStream stream = getClass().getClassLoader().getResourceAsStream("json/siteData.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            stringBufferJson.append(line);
        }
        JSONObject jobj = JSON.parseObject(stringBufferJson.toString());

        List<ResultBean> mainLPLs = Lists.newArrayList();

        ArrayList<Integer> totalAll = Lists.newArrayList();
        equipmentMaintenanceDTO.setId(-1);
        equipmentMaintenanceDTO.setAgent("a");
        equipmentMaintenanceDTO.setConfirmor("c");
        equipmentMaintenanceDTO.setEquipmentMainame("e");
        equipmentMaintenanceDTO.setModelSpecification("m");
        equipmentMaintenanceDTO.setReasons("r");
        equipmentMaintenanceDTO.setResponSiblepersion("r");
        equipmentMaintenanceDTO.setSaveAddress("s");
        equipmentMaintenanceDTO.setUnit("u");
        equipmentMaintenanceDTO.setUsePersion("u");
        equipmentMaintenanceDTO.setConfirmresult(-1);

        String exportTopTitle = "设备维修信息-" + DateUtils.formatDate(new Date(), "yyyy-MM-dd") + "导出";
        if (!IsEmptyUtils.isEmpty(equipmentMaintenanceDTO.getSdIds())) {
            String[] sdIds = equipmentMaintenanceDTO.getSdIds().split(",");
            for (String sdId : sdIds) {
                equipmentMaintenanceDTO.setSdId(Integer.parseInt(sdId));
                String dataSourceName = "";
                SiteData siteData = null;
                if (!IsEmptyUtils.isEmpty(jobj.get(sdId))) {
                    siteData = JSON.parseObject(jobj.get(sdId).toString(), SiteData.class);
                }
                if (!IsEmptyUtils.isEmpty(siteData)) {
                    dataSourceName = siteData.getDateSourceName();
                }
                if (!IsEmptyUtils.isEmpty(dataSourceName)) {
                    logger.info("--" + dataSourceName + "--");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);

                    equipmentMaintenanceDTO.setSiteName(siteData.getName());

                    Map columnWidth = new HashMap();
                    columnWidth.put(0, 5000);
                    columnWidth.put(1, 4000);
                    columnWidth.put(2, 4000);
                    columnWidth.put(3, 3000);
                    columnWidth.put(4, 12000);
                    columnWidth.put(5, 12000);

                    columnWidth.put(6, 12000);
                    columnWidth.put(7, 12000);
                    List<List<String>> topTitles = Lists.newArrayList();
                    List<String> col0 = Lists.newArrayList();
                    List<String> col1 = Lists.newArrayList();
                    List<String> col2 = Lists.newArrayList();
                    List<String> col3 = Lists.newArrayList();
                    List<String> col4 = Lists.newArrayList();
                    List<String> col5 = Lists.newArrayList();


                    List<String> col6 = Lists.newArrayList();
                    List<String> col7 = Lists.newArrayList();

                    col0.add(exportTopTitle);
                    col0.add("设备名称");
                    col1.add(exportTopTitle);
                    col1.add("规格与型号");
                    col2.add(exportTopTitle);
                    col2.add("单位");
                    col3.add(exportTopTitle);
                    col3.add("存放地点");
                    col4.add(exportTopTitle);
                    col4.add("使用人");
                    col5.add(exportTopTitle);
                    col5.add("事由");
                    col6.add(exportTopTitle);
                    col6.add("经办人");
                    col7.add(exportTopTitle);
                    col7.add("确认人");

                    topTitles.add(col0);
                    topTitles.add(col1);
                    topTitles.add(col2);
                    topTitles.add(col3);
                    topTitles.add(col4);
                    topTitles.add(col5);
                    topTitles.add(col6);
                    topTitles.add(col7);
                    ResultBean resultBean = new ResultBean();
                    resultBean.setMsg(siteData.getName());
                    resultBean.setObj(columnWidth);
                    List<EquipmentMaintenanceVO> mainLPList = equipmentMaintenanceMapper.findAllEquipmentMaintenance(equipmentMaintenanceDTO);
                    resultBean.setRows(topTitles);
                    resultBean.setResult(mainLPList);
                    mainLPLs.add(resultBean);

                }
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        } else {
            List<SiteVO> userSites = siteMapper.findUserSites(equipmentMaintenanceDTO.getUserId());
            StringBuffer stringBuffer = new StringBuffer();
            for (SiteVO siteVO : userSites) {
                equipmentMaintenanceDTO.setSdId(siteVO.getSdId());
                String dataSourceName = "";
                String sdIdStr = siteVO.getSdId().toString();
                SiteData siteData = null;
                if (!IsEmptyUtils.isEmpty(jobj.get(sdIdStr))) {
                    siteData = JSON.parseObject(jobj.get(sdIdStr).toString(), SiteData.class);
                }

                if (!IsEmptyUtils.isEmpty(siteData)) {
                    dataSourceName = siteData.getDateSourceName();
                }
                if (!IsEmptyUtils.isEmpty(dataSourceName)) {

                    logger.info("--" + siteData.getDateSourceName() + "--");

                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);

                    equipmentMaintenanceDTO.setSiteName(siteData.getName());
                    Map columnWidth = new HashMap();
                    columnWidth.put(0, 5000);
                    columnWidth.put(1, 4000);
                    columnWidth.put(2, 4000);
                    columnWidth.put(3, 3000);
                    columnWidth.put(4, 12000);
                    columnWidth.put(5, 12000);

                    columnWidth.put(6, 12000);
                    columnWidth.put(7, 12000);
                    List<List<String>> topTitles = Lists.newArrayList();
                    List<String> col0 = Lists.newArrayList();
                    List<String> col1 = Lists.newArrayList();
                    List<String> col2 = Lists.newArrayList();
                    List<String> col3 = Lists.newArrayList();
                    List<String> col4 = Lists.newArrayList();
                    List<String> col5 = Lists.newArrayList();


                    List<String> col6 = Lists.newArrayList();
                    List<String> col7 = Lists.newArrayList();

                    col0.add(exportTopTitle);
                    col0.add("设备名称");
                    col1.add(exportTopTitle);
                    col1.add("规格与型号");
                    col2.add(exportTopTitle);
                    col2.add("单位");
                    col3.add(exportTopTitle);
                    col3.add("存放地点");
                    col4.add(exportTopTitle);
                    col4.add("使用人");
                    col5.add(exportTopTitle);
                    col5.add("事由");
                    col6.add(exportTopTitle);
                    col6.add("经办人");
                    col7.add(exportTopTitle);
                    col7.add("确认人");

                    topTitles.add(col0);
                    topTitles.add(col1);
                    topTitles.add(col2);
                    topTitles.add(col3);
                    topTitles.add(col4);
                    topTitles.add(col5);
                    topTitles.add(col6);
                    topTitles.add(col7);
                    ResultBean resultBean = new ResultBean();
                    resultBean.setMsg(siteData.getName());
                    resultBean.setObj(columnWidth);
                    List<EquipmentMaintenanceVO> mainLPList = equipmentMaintenanceMapper.findAllEquipmentMaintenance(equipmentMaintenanceDTO);
                    resultBean.setRows(topTitles);
                    resultBean.setResult(mainLPList);
                    mainLPLs.add(resultBean);
                }
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }
        return mainLPLs;
    }
}
